import React, { Component } from 'react';
import PropTypes from 'prop-types';

import emitter from './events';

class ListItem extends Component {
  static defaultProps = {
    checked: false
  }
  constructor (props) {
    super(props);
  }
  render () {
    return (
      <li>
        <label>
          <input type="checkbox" checked={this.props.checked} onChange={this.props.onChange}/>
          <span>{this.props.value}</span>
        </label>
      </li>
    )
  }
}

class List extends Component {
  constructor (props) {
    super(props);
    this.state = {
      list: this.props.list.map(entry => ({
        text: entry.text,
        checked: entry.checked || false
      }))
    };
  }
  onItemChange (entry) {
    console.log(entry)
    const {list} = this.state;
    this.setState({
      list: list.map(item => ({
        text: item.text,
        checked: item.text === entry.text ? !entry.checked : item.checked
      }))
    });
    emitter.emit('ItemChange', entry);
  }
  render() {
    return (
      <div>
        <ul>
          {
            this.state.list.map((item, index) => (
              <ListItem key={index} checked={item.checked} value={item.text} onChange={this.onItemChange.bind(this, item)}></ListItem>
            ))
          }
        </ul>
      </div>
    );
  }

}

export default List;
